<template>
	<scroll-view 
		v-if="dynamicList.length"
		class="setup-content" 
		:scroll-x="false"
		:show-scrollbar="false"
		scroll-y
		@scrolltoupper="scrolltoupper" 
		@scrolltolower="scrolltolower" 
		@scroll="onScroll"
		style="height: 100vh;"
		>
		<view class="title">
			<image src="/static/icon/dynamic.png" style="width: 30px;height: 30px;"></image>
			<view class="label">手机使用实时动态(孩子锁屏后无数据上传)</view>
		</view>
			<uni-steps 
			    class="van-steps-component"
				:options="dynamicList" 
				direction="column"
				:active="dynamicList.length" 
				active-icon="success"
				active-color="#2BC888"  
				inactive-color="#000">
				</uni-steps>
				<view class="refresh" @click="refresh"></view>
	</scroll-view>
	<view v-else class="loading-sytle">
		<Empt description="暂无动态" />
	 </view>
</template>

<script setup lang="ts">
	import { ref, computed, nextTick} from 'vue';
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import { dynamicServer } from "@/common/index";
	import Empt from "@/components/Empt/index.vue"
	import {onShow} from "@dcloudio/uni-app"
	import { useBound } from "@/hooks/useBound.ts"
	import { mock, timeFormatHelp } from "@/utils/index"

	
			
	const SIZE_NUM = 20;
	const {tipBoundStudent, studentIsEmpt} = useBound();
	const studentStore = useStudentListStore();
	const curStd = computed(() => studentStore.currentStudent);
	
	const vipExpireDate = computed(() => {
		if(studentIsEmpt.value){
			return false;
		}
		if(curStd.value?.expireDate){
			const day = timeFormatHelp.daysDifference(curStd.value.expireDate);
			return day <= 0
		} else {
			return false
		}
	})
	
	const size = ref(SIZE_NUM);
	const page = ref(1);
	const direction = ref<'up' | 'down'>('up'); // up: 上 down: 下
	const finished = ref(false); // true: 列表全部加载完成，不能再请求接口， false: 还可以继续下拉加载数据
	const scrollTop = ref(0)
	const onScroll = (event) => {
		scrollTop.value = event.detail.scrollTop;
	}
	
	const customDescClass = computed(() => {
		return {
			marginTop:"15upx",
			color:"blue"
		}
	})
	const scrollToPosition = async (position) => {
	  await nextTick(); // 确保DOM更新完成
	  uni.pageScrollTo({
	    scrollTop: position,
	    duration: 0 // 立即滚动到位
	  });
	};
	
	const dynamicList = ref([])
	// 设置mock 数据
	const setMock = () => {
		const data = mock.INDEX_DY.data
		finished.value = true;
		let list = data.map(item => {
			item.desc = item.createdDate;
			item.title = item.eventName;
			return item;
		})
		console.log('mock实时动态数据', list)
		dynamicList.value = list;
	}
	// 实时动态
	const dynamic = async () =>{
		const studentId = curStd.value?.id;
		if(studentId){
			try{
				// 更新前记录滚动位置
				const currentScrollTop = scrollTop.value;
				uni.showLoading({
					title:"加载中..."
				})
				const { status, data} = await dynamicServer.dynamic({studentId, page:page.value, size: size.value});
				if( status === '200'){
					if(direction.value === "up"){
						 finished.value = false;
						 let list = data.map(item => {
							item.desc = item.createdDate;
							item.title = item.eventName;
							return item;
						 })
						 dynamicList.value = list;
					}
					 // 数据更新后，恢复滚动位置
					 if(direction.value === "down"){
							if(data.length === 0) {
							   finished.value = true;
							} else {
							  let list = data.map(item => {
								item.desc = item.createdDate;
								item.title = item.eventName;
								return item;
							  })
							  dynamicList.value = dynamicList.value.concat(list);
							  finished.value = false;
							}
						scrollToPosition(currentScrollTop);
					 }
				}
				uni.hideLoading();
			}catch(e){
				console.log(e)
			}
		} else {
			console.log('没有学生id, 无法查询实时动态')
		}
	};
	

	
	onShow(() => {	
		const reset = () => {
			page.value = 1;
			size.value = SIZE_NUM;
			dynamicList.value = [];
			console.log("清空了所有数据")
		}
		
		if(vipExpireDate.value){
			uni.showModal({
				title:"您的孩子VIP已到期",
				content:"温馨提示， 尊敬的家长，您的孩子的账号 VIP 已到期，管控功能即将失效，避免影响使用，请立即续费, 感谢您的支持！",
				confirmText:'购买会员',
				success(res) {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pagesB/memberCenter/index'
						})
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})
			reset();
			return 
		}
	
		if(!mock.isLogged()){
			setMock()
			return;
		}
		
		if(studentIsEmpt.value){
			reset()		
			tipBoundStudent()
			return;
		} else {
			reset()
			dynamic()
		}
	})
	
	// 刷新
	const refresh = () => {
		if(!mock.isLogged()){
			tipBoundStudent()
			return;
		}
		direction.value = "up";
		//  所有数据都需要重置
		page.value = 1;
		size.value = SIZE_NUM;
		finished.value = false
		dynamicList.value = [];
		dynamic();
	}
	
	//  滚动到顶部
	const scrolltoupper = () => {
		if(studentIsEmpt.value){
			return;
		}
		direction.value = "up";
		//  所有数据都需要重置
		page.value = 1;
		size.value = SIZE_NUM;
		finished.value = false
		dynamicList.value = [];
		dynamic();
		// uni.stopPullDownRefresh();
	};
	
	const sleep = (t = 1000) => {
		return new Promise((resolve, reject) => {
			setTimeout(resolve, t)
		})
	}
	//  触底加载
	const scrolltolower = async () => {
		sleep()
		if(studentIsEmpt.value){
			return;
		}
		if(finished.value){
			uni.showToast({
				title:"实时动态已全部加载完毕",
				icon:'none'
			})
			return;
		}
		direction.value = "down";
		//  所有数据都需要重置
		page.value++;
		dynamic();
	};
	
</script>

<style lang="scss">
	page {
		background-color: #f5f9fa;
	}


</style>

<style lang="scss" scoped>
	.loadingHomePage{
		background-color: rgba(0, 0, 0, 0.3);
		width: 100vw;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.loading-sytle{
		// background-color: rgba(0, 0, 0, 0.1);
		background-color: #fff;
		width: 100vw;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		position: fixed;
		z-index: 10;
		top:0;
		left: 0;
		right: 0;
		bottom: 0;
	}
	.dynamic-page {
		position: relative;
		.main {
			margin-top: 40upx;
			padding: 30upx 17upx;
			background-color: #fff;
			height: 100vh;

			

		}

		.sticky {
			position: fixed;
			bottom: 100upx;
			right: 50upx;
		}
	}
	
	
	.title {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		padding: 20upx 20upx;
		.label {
			margin-left: 16upx;
			font-weight: 600;
			font-size: 26upx;
			color: #333333;
		}
	}
	
	.setup-content {		
		.desc-class {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28px;
			color: #999999;
		}
	}
	
</style>

<style lang="scss">
	.setup-content {
		.van-steps{
			min-height: calc(100% + 50upx);
		}
	}
	
	.van-steps-component{
		height: 100%;
		padding-bottom: 50upx;
		.van-step{
			padding: 30upx 0;
			.van-step__title{
				line-height: 50upx;
			}
		}
		
	}
</style>

<style scoped lang="scss">
	.refresh{
		position: fixed;
		right: 24upx;
		bottom: 126upx;
		width: 108upx;
		height: 108upx;
		background: url("/static/icon/refresh.png") center center no-repeat;
		border-radius: 50%;
		background-size: cover;
	}
</style>

<style lang="scss">
	.uni-steps__column-text{
		padding: 16px 0px;
		.uni-steps__column-title{
			// margin-top: 20upx;
			padding-bottom: 20upx;
		}
	}
	.uni-steps__column-line-item{
		min-height: 60px;
	}
	.uni-steps__column-title, .uni-steps__column-desc{
		color: #000 !important;
	}
</style>